#include <hdf/mfhdf.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, const char *argv[]) {
  int channel;
  int source, target;
  int source_file, target_file;
  long size[2], start[2], origo[2];
  const char *source_name = argv[1];
  const char *target_name = argv[2];
  char temp[256];
  char *buffer;
  start[0] = atoi(argv[3]);
  start[1] = atoi(argv[4]);
  size[0] = atoi(argv[5]);
  size[1] = atoi(argv[6]);
  origo[0] = 0;
  origo[1] = 0;
  buffer = malloc(size[0] * size[1]);
  source_file = SDstart(source_name, DFACC_READ);
  for (channel = 0; channel < 3; ++channel) {
    source = SDselect(source_file, channel);
    SDreaddata(source, start, NULL, size, buffer);
    SDendaccess(source);
    sprintf(temp, "dataset_%d", channel + 1);
    if (channel == 0) {
      target_file = SDstart(target_name, DFACC_CREATE);
    } else {
      target_file = SDstart(target_name, DFACC_WRITE);
    }
    target = SDcreate(target_file, temp, DFNT_UINT8, 2, size);
    SDwritedata(target, origo, NULL, size, buffer);
    SDendaccess(target);
    SDend(target_file);
  }
  SDend(source_file);
  free(buffer);
  return 0;
}
